const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../utils/user.js');

//获取应用实例
const app = getApp();

Page({
  data: {
    newGoods: [],
    hotGoods: [],
    topics: [],
    brands: [],
    groupons: [],
    floorGoods: [],
    banner: [],
    channel: [],
    coupon: [],
    articles:[],
    goodsCount: 0,
    indicatorDots: false,
    window: false,
    colseCoupon:false,
    MyMenus: [
      { url: "/pages/popular/index?id=1", pic: "1.jpg",name:"肾病"},
      { url: "/pages/popular/index?id=2", pic: "2.jpg", name: "糖尿病" },
      { url: "/pages/popular/index?id=3", pic: "3.jpg", name: "肝病" },
      { url: "/pages/popular/index?id=4", pic: "4.jpg", name: "肿瘤" },
      ],

  },

  onShareAppMessage: function() {
    let userInfo = wx.getStorageSync('userInfo');
    let shareUserId = 1;
    if (userInfo){
      shareUserId = userInfo.userId;
    }
    console.log('/pages/index/index?shareUserId=' + shareUserId);
    return {
      title: '哲卉',
      desc: '',
      path: '/pages/index/index?shareUserId=' + shareUserId
    }
  },

  onPullDownRefresh() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.getIndexData();
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
    this.getCache();
  },
  getCache:function(){
    util.request(api.CacheUrl, {
      key: "Dts_cache"
    }).then(function(res) {
        console.log("刷新",res)
    })
  },
  getIndexData: function() {
    let that = this;
    wx.showModal({
      title: '订阅提示',
      content: '为了通知您办理进度，需要向您推送相关消息',
      success: function(res) {
        if (res.confirm) {
          console.log(confirm)
          that.openPopup();
        }
      }
    })
    

    util.request(api.IndexUrl).then(function(res) {
      if (res.errno === 0) {
        that.setData({
          newGoods: res.data.newGoodsList,
          hotGoods: res.data.hotGoodsList,
          topics: res.data.topicList,
          brands: res.data.brandList,
          floorGoods: res.data.floorGoodsList,
          banner: res.data.banner,
          articles: res.data.articles,
          groupons: res.data.grouponList,
          channel: res.data.channel,
          coupon: res.data.couponList
        });
      }
    });
    util.request(api.GoodsCount).then(function (res) {
      that.setData({
        goodsCount: res.data.goodsCount
      });
    });
  },
  onLoad: function(options) {
      console.log(options)
    this.setData({
      colseCoupon: false
    });
    //如果有分享用户，则设置
    // if (options.shareUserId){
    //   wx.setStorageSync('shareUserId', options.shareUserId);
    // }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.scene) {
      //这个scene的值存在则证明首页的开启来源于朋友圈分享的图,同时可以通过获取到的goodId的值跳转导航到对应的详情页
      var scene = decodeURIComponent(options.scene);
      console.log("scene:" + scene);
      // this.setData({
      //   'scene': scene
      // });
      wx.setStorageSync('scene', scene);
      console.log("sss", wx.getStorageSync('scene'));
      let scene2 = wx.getStorageSync('scene');
      console.log("sec2",scene2)
      // let info_arr = [];
      // info_arr = scene.split(',');
      // let _type = info_arr[0];
      // let id = info_arr[1];

      // let shareUserId = null;//默认用户
      // if (info_arr.length == 4 && info_arr[2] == 'user'){
    	//   shareUserId = info_arr[3];
      // } else if (_type == 'user'){
    	//   shareUserId = id;
      // }

	
  	
      // if (_type == 'goods') {
      //   wx.navigateTo({
      //     url: '../goods/goods?id=' + id
      //   });
      // } else if (_type == 'groupon') {
      //   wx.navigateTo({
      //     url: '../goods/goods?grouponId=' + id
      //   });
      // } else if (_type == 'brand') {
      //     wx.navigateTo({
      //         url: '../brandDetail/brandDetail?id=' + id
      //       });
      // } else if (_type == 'topic') {
      //      wx.navigateTo({
      //          url: '../topicDetail/topicDetail?id=' + id
      //        });
      // } else {
      //   wx.navigateTo({
      //     url: '../index/index'
      //   });
      // }
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.grouponId) {
      //这个pageId的值存在则证明首页的开启来源于用户点击来首页,同时可以通过获取到的pageId的值跳转导航到对应的详情页
      wx.navigateTo({
        url: '../goods/goods?grouponId=' + options.grouponId
      });
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.goodId) {
      //这个goodId的值存在则证明首页的开启来源于分享,同时可以通过获取到的goodId的值跳转导航到对应的详情页
      wx.navigateTo({
        url: '../goods/goods?id=' + options.goodId
      });
    }

    if (options.orderId) {
      wx.navigateTo({
        url: '../ucenter/orderDetail/orderDetail?id=' + options.orderId
      });
    }

    this.getIndexData();
    this.getCache();
  },
  onReady: function() {
    // 页面渲染完成
    let that = this;
    let userInfo = wx.getStorageSync('userInfo');
    if (!that.data.colseCoupon && userInfo && that.data.coupon.length > 0) {
      that.setData({ window: true });
    }
  },
  onShow: function() {
    // 每次页面显示，需获取是否用户登录，如果用户登录，则查询用户是否有优惠券，有则弹出优惠券领取窗口
    let that = this;
    let userInfo = wx.getStorageSync('userInfo');
    // if (userInfo){
    //   util.request(api.GetUserCoupon, null, 'GET').then(res => {
    //     if (res.errno === 0) {
		//     that.setData({
		//           coupon: res.data.couponList
		//    });
		   
		//    if (!that.data.colseCoupon && userInfo && that.data.coupon.length > 0) {
		//       that.setData({ window: true });
		//    } else {
		//       that.setData({window:false});
		//    }
    //     }
    //   })
    // }

  },
  onHide: function() {
    // 页面隐藏
  },
  onUnload: function() {
    // 页面关闭
  },
  onColse: function () {
    this.setData({
       window: false,
       colseCoupon:true
     });
  },

    // 是否设置过授权
    openPopup() {
      const _this = this;
      // 获取用户的当前设置，判断是否点击了“总是保持以上，不在询问”
      wx.getSetting({
        withSubscriptions: true, // 是否获取用户订阅消息的订阅状态，默认false不返回
        success(res) {
          console.log('res.authSetting', res.authSetting)
          if (res.authSetting['scope.subscribeMessage']) {
            console.log('用户点击了“总是保持以上，不再询问”')
          } else {
            console.log('用户没有点击“总是保持以上，不再询问”则每次都会调起订阅消息')
            //因为没有选择总是保持，所以需要调起授权弹窗再次授权
            _this.authorizationBtn();
          }
        }
      })
    },
   
      // 授权
    authorizationBtn() {
      console.log("进来了7")
      wx.requestSubscribeMessage({
        tmplIds: ['xZOSySoGqIy4YJMnPUDHT_VrTAPJVcvCyYc_kbivAh0', 'tV_1SiEk0z-iXeqZKVYR8Cjhyd6sgog8QxsDixC-L0w','_ZLO21_NVm8szcEZqBjRzNOJkliQQkzELTe05Th0nQ4'],
        success(res) {
          console.log(res,'授权成功')
        },
        fail (error) {
          console.log(error)
          console.log(error);
        }
      })
    },
    goPages:function(e){
      wx.navigateTo({
        url: e.currentTarget.dataset.url
      });
      // if (this.data.hasLogin) {
      //   wx.navigateTo({
      //     url: e.currentTarget.dataset.url
      //   });
      // } else {
      //   wx.navigateTo({
      //     url: "/pages/auth/login/login"
      //   });
      // };
    },
})